home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Gold Medal Software 3
/
Gold Medal Software - Volume 3 (Gold Medal) (1994).iso
/
prog
/
prog914.arj
/
PROGTEXT.DOC
< prev
next >
Wrap
Text File
|
1994-01-08
|
40KB
|
948 lines
PROGTEXT.DOC - by: Ira F. Kavaler - March and April, 1987
Beginner's BASIC - Ira F. Kavaler - 3/14/85 - 1/8/94
The BASIC Language.
-------------------
BASIC is the name of a high-level computer language that is
furnished with the vast majority of personal computers. BASIC stands
for Beginners All-Purpose Symbolic Instruction Code. BASIC is not a
new language; it has been in use for 25 years. It is not an original
language; it was derived from the most popular language of all time,
FORTRAN (FOrmula TRANslator). Both of these languages were created for
scientists and engineers; however, since both have become very easy to
use in the past decade, almost every field where computers can be
beneficial, BASIC (and FORTRAN) can be used as a general purpose
programming language.
BASIC consists of a set of "commands". A command is a word or an
abbreviation that tells the computer to perform a task. Commands
usually require some additional information called "arguments" which
specify the object of the task. An instruction or "statement" contains
the total information, command and argument(s). The statements are
arranged in a logical sequence to produce a "program".
Line Numbers.
-------------
If you have ever followed a set of instructions you have noticed
that each instruction is given a number. This number serves two
purposes:
1. To determine the proper order (sequence) of the instructions, and
2. To provide a reference to any specific instruction should that
become necessary.
The computer program also uses such a numbering system for the
same reasons; each statement number is called a "line number" since
each statement in the program is usually written one to a line. "Line
numbers" must be positive integers; that is, zero, negative numbers,
and non-whole numbers areNot allowed.
You might want to number your lines starting with "1" and
continuing, incrementing the number by one, until all lines have been
numbered. Although there is no reason why this method would not work,
a much better practice is to start with line number "10" and continue
incrementing each subsequent line number by ten. The advantage is that
if you have forgotten a statement in theMiddle of the program, you will
have unused numbers in-between the existing line numbers.
Nearly 90% of all computer programs can be written using only six
easily understood elementary commands: LET, PRINT, INPUT, GOTO,
IF...THEN, and END. There are dozens of other commands that make
writing a program a very simple and concise task; however, you will
discover that they areSubstitutes for commonly encountered sequences of
the six elementary commands.Numeric constants.
For many years the art of computer programming was kept a deep,
dark secret by the mathematicians of the world. By the way, computer
programmers were called mathematicians in the "olden days" (1930's
through 1960's). In order to retain the secret, many mysterious terms
were either adopted or coined for the computer and programming
vocabulary; "constant" is such a term. A "constant" is a number which
represents a quantity or an amount. In general, a "constant" is
anything that is fixed in value. To be more precise, this type of
constant is called a "numeric constant", as it only pertains to
quantities or amounts. Constants are like the numbers you would enter
into a calculator:
the digits zero "0" through nine "9",
the decimal point ".",
the plus "+" and minus "-" signs
(which denote positive and negative Numbers), and
the letter "E" (exponent) is also used as a symbol to indicate
scientific notation (10 to a power).
On a scientific calculator the key is labelled either "EE" (enter
exponent) or "EXP".
1234567890 = 1.23456789 X 10 (to the 9th power)
= 1.23456789E+9
0.0002468 = 2.468 X 10 (to the minus 4th power)
= 2.468E-4
There is another category called "string constants" that involves
names, addresses, dates, etc. "Strings" will be covered at a later
time.
Flow Charting.
--------------
The easiest way to start writing a program is to diagram it; that
is, diagram the steps necessary to solve the problem. Over the years
some symbols have been adopted by different disciplines for this
purpose. These symbols are not standardized, and are left to you to
use what you feel confortable using. The following are my set:
BASIC Command Flow chart symbol
------------- -----------------
LET a rectangle
INPUT a rectangle with the upper left corner cut-off
(so it looks like a computer punch card)
PRINT a rectangle with a one cycle sine wave at the
bottom
(so it looks like a sheet of paper torn-off)
STOP or END an octagon
(so it looks like a stop sign)
IF...THEN a diamond
the program first line an upside-down triangle
(so it looks like a yield sign)
GOTO a circle (see text)
The flow chart symbols are interconnected with arrows showing the
direction of progress from one command to the next. Exclding the
IF...THEN diamond, each symbol can only have one aroow leaving it, but
can have one or more arrows poinmting to it.
The IF...THEN diamond must have only two arrows leaving it, one if
the logical expression is evaluated "true" and the other if the logical
expression is evaluated "false". It can have one or more arrows
poinmting to it.
The STOP or END octagon cannot have any leaving arrows. (There is
one very advacned condition, where a CONTINUE command is executed, that
allows for a leaving arrow, but it is seldom used.)
The GOTO is normally not symbolized, the arrows are just drawn to
indicate the path of the GOTO; however, if the destination of the GOTO
is far away from the source of the GOTO, or it is on another sheet of
paper, etc., the source GOTO is terminated in a circle which has a
specific label; the destination of the GOTO originates at a circle
having the same label, with an arrow to the destination command.
The REM command is not indicated on the flow chart.
Numeric Variables.
------------------
As some of the better calculators have memories which can hold
numbers, the computer also has memories. Usually the calculator's
memories will be numbered: M1, M2, M3, etc. One problem is that you
must remember which memory holds what constant.
The computer does not number the memories, but instead allows you
to give them names. If you wanted the computer to hold the balance of
your checking account, you could call it BALANCE. The computer will
automatically assign one of its memories for this purpose and use it
anytime you specify BALANCE. Similarly, you could hold the deposit you
made to your account as DEPOSIT, and there would be no problem. In
fact, the computer has the ability to hold hundreds of memories,
limited only by the "size" of your computer system. These so-called
memories that you can name for your specific purpose are called
"variables", and since they hold "numeric constants", they are called
"numeric variables". But I now must clarify one point; most computers
only use the first two characters of the variable name, although your
name may be upto 16 characters long. The IBM and compatibles use all
16 characters. Consider a program where you are a farmer and have to
keep track of how many apples and apricots you have harvested. If you
use the variable names APPLES and APRICOTS, most computers will not
keep the two constants in separate variables; both "APPLES and
APRICOTS start with the same two letters "AP", and if the computer only
uses the first two characters when it assigns memory to the variable
names. You will have to choose a different name for one of the two
names, such as "ap" for apples and "ar" for apricots.
You can name your variables using one letter of the alphabet ("A"
through "Z"), two letters ("AA" through "ZZ"), or a letter followed by
a number ("A0" through "Z9"). No other characters found on the
computer's keyboard are allowed in variable names, no punctuations, no
symbols, no arithmetic operations, and no "spaces".
If you calculate how many different variable names you can create
fromThe above rules, you will get 962 (=26+676+260).Arithmetic
operations. As your calculator has arithmetic operations: addition,
subtraction, multiplication, and division, so does the computer. The
symbols for multiplication and division are different on the computer;
multiplication isIndicated by "*" (called an "asterisk" or "star"), and
division is indicated by "/" (called a "slash")".
The LET Command.
----------------
The most often used command in any computer program is the LET
command. It performs three functions:
1. It initializes a variable to a specific constant.
The form of the command is:
10 LET variable = constant
Notice that 10 is an arbitrary line number, the command LET follows,
the variable name must be next, then an equal sign, followed by a
constant.
2. It sets the current value in one variable to another variable.
The form is only slightly different:
20 LET variable2 = variable1
This instruction would recall the value of variable1 and store that
value in variable2.
3. It evaluates an arithmetic expression and store the answer in a
variable. The form now becomes:
30 Let variable = arithmetic expression
Where the arithmetic expression is any combination of variables,
constants, and arithmetic operations that represents a formula. In all
three forms of the LET command, only one variable name is allowed to
the left of the equal sign, only one equal sign follows, and the
remainder of the instruction is to the right of the equal sign.
When aa arithmetic expression, a formula, is used you must follow
a set on algebraic conventions used in mathematics. These convenmtions
are very similar to those you use when you are using a hand calculator.
Symbol Name Purpose
------ ------------ -------
+ Plus Sign Used for adding or
indicating a positive value.
- Minus Sign Used for subtracting or
indication a negative number.
* Star or Asterisk Used for multiplying
(x and . cannot be used).
/ Slash or Fraction Bar Used for dividing
(there's no line with two dots).
^ Carat Used for raising to a power
(there's no superscript).
( Left or Open Parenthesis Used to start a priority
calculation.
) Right or Close Parenthesis Used to end a priority
calculation.
The order of arithmetic & logical operations (hierarchy) is:
1. Inner-most parentheses & functions
2. Outer-most parentheses & functions
3. Exponentiation
4. Multiplication & division (left to right)
5. Addition & subtraction (left to right)
6. Logical comparative operations (=,<,>,etc.)
7. Logical conjunctive operations (AND, OR, NOT)
It is also important to note that the command LET is optional and
thus is usually omitted from the statement:
10 Velocity=88
20 X2=x1
30 Area=base*height/2
LET is the only command that is optional, all other commands must
immediately follow the line number, as will be seen in later commands.
Syntax.
-------
In describing the elements that comprise the various forms of the
LET Command, I tried to stress their proper order. This order can be
related to the correct order of the parts of a sentence, referred to as
grammar. The grammar of a program statement is called "syntax"
(sin'tacks). If you have taken the time to sit down at the computer
keyboard and typed in a program, you have probably encountered a
message from the computer. All it means is that the computer did not
understand the syntax in line 40 when it tried to follow the statement.
A syntax error can be caused by aNumber of things:
1. The command was misspelled or an unknown command was used,
2. The command was accompanied by incorrect or missing punctuation,
3. A variable had the same name as a command, or
4. An arithmetic operator was used incorrectly.
Housekeeping (simple editing).
You are bound to make many mistakes, most will be typos. When you
do, the line numbers which you have given to each statement will assist
you in correcting the mistakes. If you have to delete a line, just
type the line number of that statement and press the ENTER key. (On
many computers this key is labelled RETURN.) What you have done is to
replace the statement with nothing; the computer realizes this and
merely deletes the statement. For the time being, if you make a typo,
just retype the statement correctly using the same line number. The
computer will automatically remove the old statement and replace it
with the new statement you have just typed in. When we discussed "line
numbers" we said that we could insert new statements in between
existing line numbers. If you are asking yourself how does the new
statement get "in between", relax. The computer automatically keeps
track of which line numbers have been used and what line numbers
isBeing type in. As soon as you press the ENTER key, the computerLooks
to see where the new line number should go:
delete the line,
replace the line,
place the new line at the current end of the program,
place the new line at the start of the current program, or
place the new line in between any of the existing lines.
This automatic resequencing of program instructions is sometimes
called "housekeeping", as the computer is cleaning-up the order in
which you have entered your program.
The PRINT Command.
------------------
Unlike a calculator, whenever the computer does a LET command (the
same as pressing "=" on the calculator) the computer does not show the
answer on the video screen (also called a monitor, CRT, or video
display). The computer merely stores the answer in the variable name
you have chosen. In order to tell the program to display an answer
(the current constant stored in a variable) you have to issue a PRINT
command. The general form of the command is:
PRINT variable
The term "print" is from the "olden days" when the only device
that the computer had connected to it to display answers was a
lineprinter or teletype. For these devices, "print" was a good choice
of command as both devices actually printed the answers.
40 PRINT BALANCE
In the above example, the current value of BALANCE is printed at
the left edge of the next (lower) empty line on the screen. If the
screen was totally empty before the PRINT, the top line of the screen
would show the answer. If the screen was completely filled, everything
on the screen would automatically move up one line (scroll up) thus
emptying a line at the bottom of the screen where the answer could now
be printed. The former top line of the display would be lost (erased).
The computer keeps track of the condition of the screen by use of
an "pointer". Usually the position of the pointer is not indicated on
the screen; however, when you have to type something into the
computer, the computer shows you where it will appear on the screen by
displaying its pointer. When the pointer is visible on the screen it
is called a "cursor". On many computers the cursor is nothing but a
flashing block of light, on other computers the cursor may appear as a
steady underline. If you see the cursor you can be sure that the
computer is waiting for you to supply some information.
It is possible to print more than one thing on a screen line.
More than one variable can be shown after a PRINT command:
50 PRINT BALANCE,DEPOSIT
60 PRINT AP;AR
In both lines 50 an 60 two variables are printed on each line. In
line 50 the two variables (BALANCE and DEPOSIT) are separated by a
comma ",". The comma tells the PRTINT command to display the answers
in columns (tabulate). The positions on the screen that determine
where the columns start is fixed within the computer system, depending
on the width (number of characters) of the screen. The IBM and
compatibles computers have five columns per line as its width is 80
characters. Each column width is usually set so that the longest
(highest accuracy) number will not normally span adjacent columns. In
line 60 the two variables (AP and AR) are separated by a semicolon ";".
The semicolon tells the computer not to tabulate the answers into
columns, but rather print one after another with a minimum number of
spaces.
The choice of whether to print one or more variables per line,
whether to use commas or semicolons if you decide to print more than
one per line, is up to you. You will soon develope a habit and then a
sense for what to do. Many times you will choose one way, just to
change it to another, or a third way, after you have seen the answers
on the screen. When you get a few hours of programming under your
belt, you will find that you spend as much, or even more time changing
the structure of the PRINT commands just to make to screen look pretty!
You can "quote" me.
Besides displaying the answers to calculations, the PRINT command
canBe used to display messages on the screen. These messages are used
to give the person running the program additional information. The
form of the command becomes:
PRINT "any message or group of characters"
Note that the message is enclosed in quotes ("). In fact, the quoted
message is nothing more than a substitute for a variable name that
would normally be found in a PRINT statement; thus any number of
quoted messages and/or variable names can be intermixed within the
PRINT statement. Commas and/or semicolons can be used at the
programmers discretion to separate the arguments.
10 PRINT "The balance is $";B
20 PRINT "The speed is";S;"mph"
30 PRINT W;"gallons of water"
40 PRINT "Time","Distance"
In line 10 the addition of the dollar sign "$" emphasizes the amount of
money. In line 20 the addition of "mph" gives the units of the speed.
Line 40 showns
that messages alone may be displayed.
The INPUT Command.
------------------
In order to make a computer program useful it is necessary to get
different information into the computer each time the program is used.
Remember, the program is nothing more than the set of instructions.
Although the LET commands give constants to the calculations, they are
not sufficient. What we want is a command that will allow the program
to ask the person questions pertaining to the specific application of
the problem. The INPUT command allows this flexibility. The general
form is:
INPUT variable name
When the computer performs this command it stops, displays a
question mark "?" and the flashing cursor, and awaits a response from
the person. The response is understood by the computer to be the
"constant" for that variable name. Once the constant is typed onto the
keyboard, the person signals to the computer that the constant is
complete by pressing the ENTER key. The computer will extinguish the
cursor and continue the program with the new information.
More than one constant may be requested by the INPUT command by
simply having additional variable names, each separated by a comma,
(semicolons are not permitted). When multiple constants are required,
the person enters each constant separated by a comma, pressing the
ENTER key after the last constant. If the ENTER key is pressed before
all constants are entered, the computer will respond with two question
marks "??", indicating that more information is required. Conversely,
if too many constants are entered (more than there are variable names
in the INPUT statement), the program will continue without error;
however, a warning message of "extras ignored" will be displayed.
60 PRINT "How many checks"
70 INPUT NC
In line 60 the PRINT command asks the person a question. Line 70
allows the program to accept the response and stores the value in
variable name NC. Except for the question mark and flashing cursor,
the INPUT command Imparts no information about the nature of the
question. It is up to the programmer to PRINT a message called a
"prompt".
Since this sequence of PRINT and INPUT commands is common, there
is a version of the INPUT command that contains a place for the
message, this version of the command is called a "prompted input":
INPUT "prompt message";variable name(s)
The "prompt" must always immediately follow the INPUT command and be
enclosed in quotes, then followed always by a semicolon, and then
followed by any number of variable names, each separated by a comma:
60 INPUT "How many checks";NC
This is how the previous two commands can be combined into a single
"prompted input" command. (Line 70 is not required.) The only
difference would be that the prompt and response are displayed on the
same line on the screen when the program is run.
One of the most common errors occurs when you enter constants. You
accidentally press a character, such as a letter, instead of a digit,
decimal point, plus or minus sign, or the letter "E". When this
happens the computer will respond with a warning message "redo from
start". The computer will force you to reenter the all constant(s)
correctly, and then continue the program.
It's time to write a program.
We are going to write a program that will determine the number of
single rolls of wallpaper needed for a room, given the size of the
room. First we will list the steps that must be taken to solve the
problem:
1. Ask the person the size of the room in feet by:
A. Asking for the room length in feet,
B. Asking for the room width in feet, and
C. Asking for the room height in feet.
2. Calculate the amount of wallpaper required by:
A. Calculating the perimeter of the room in feet,
B. Calculating the wall area in square feet, and
C. Calculating the number of single rolls by dividing the wall
area by 30 square feet.
3. Tell the person the number of single rolls required.
Having listed the steps in the process, we can translate each step
into a program statement:
10 PRINT "Enter the size of the room."
20 INPUT "Length (in feet)";L
30 INPUT "Width (in feet)";W
40 INPUT "Height (in feet)";H
50 P=W+W+L+L
60 A=P*H
70 N=A/30
80 PRINT "You will need";N
90 PRINT "single rolls of wallpaper."
Where: L=length, W=width, H=height, P=perimeter, A=area, N=number of
rolls.
Direct and Immediate Commands.
------------------------------
There are a few commands that usually do not appear in a program
but are used to make the computer operate its various feature:
The RUN Command.
----------------
Once you have typed in the program this command tells the computer
to start the program running. When the computer finishes the last
(highest numbered) line, the computer will automatically stop. (STOP
and END are commands that can be put anywhere in a program to make the
program stop not necessarily at the last line).
The LIST Command.
-----------------
This command allows you to display the program on the screen,
starting with the first line through the last line. The screen will
normally scroll fast. To stop the scrolling it is necessary to press
the CTRL (Control) and BREAK key simultaneously, or the ESC (Escape)
key.
The NEW Command.
----------------
This command will erase the program from the computer. Do not use
this command unless you are sure you do not want the program. The NEW
command should only be used when you are ready to type in a completely
new program.
Continuing with the Program.
----------------------------
With the program typed in the computer, reread it to be sure there
are no typing errors. Retype correctly any line that has an error.
Now type the command RUN and press the ENTER key. The program will
display the first of the series of three questions dealing with the
size of the room. Answer each question with a number (constant),
pressing the ENTER key after each response. Immediately the computer
will display the answer to the problem, and will then say "Ready",
meaning that the program has "stopped running". You may now type RUN
again to get the answer for another room size.
Making the Program even Better.
-------------------------------
You should realize that the room has doors and windows, and that
you will need less wallpaper since the wall area is reduced. Let's
modify the program to include this feature. We will have to add steps
to the solution of the problem:
Change old step 3. To new step 6. And replace it with:
3. Ask the person for the number of doors in the room.
4. Ask the person for the number of windows in the room.
5. Calculate the roll reduction by:
A. Adding together the number of doors and windows,
B. Reducing the numbers of rolls by subtracting 1/2 Roll
for each (door/window) opening.
6. Tell the person the number of single rolls required.
We can now add the extra program lines to the previous version of
the program by typing in only these new lines:
72 INPUT "How many doors";ND
74 INPUT "How many windows";NW
76 OP=ND+NW
78 N=N-0.5*OP
Where: ND=number of doors, NW=number of windows, and OP=number of
openings (Doors+windows).
Notice that the rest of the program did not have to beRetyped.
If you now type LIST (and press RETURN) you will see that the
program contains the newly added lines in their proper position. Now
type RUN (and press RETURN), answer all the questions, and observe that
the answer has been changed (from what would have been previously
displayed) to account for the savings in wallpaper due to the door(s)
and window(s) decreasing the wall area.
Entangled in Red Tape.
----------------------
After you type in a program you will wonder what is going to
happen to that program once you turn off power to the computer. Your
program is going to be lost forever. Not a very pleasant thought
considering you have probably just invested a few hours getting it to
run just the way you wanted. There are a series of commands that give
you the ability to save your programs on a disk (also called a diskette
or floppy disk) for future use, or to exchange them with a friend who
has the same computer system. IBM and compatibles can use the same
diskettes.
The SAVE Command.
-----------------
To save a program to a disk, insert the disk into the floppy drive
by holding the disk by the label end, and inserting it into the drive
with the label up. Type in the command:
SAVE "a:filename" or SAVE "b:filename"
Where "a:" is the designation for your first floppy drive, and
"filename" is any name you want to give your program, enclosed in
quotes. This name allows the computer to find the program at a later
time. If you have a second floppy drive its designation is "b:".
Since you are starting fresh out in BASIC programming I would
suggested that you save the program in the ASCII format so that it can
be reloaded into an editor. You do this by appending a comma and the
letter "a" (for ASCII) to the end of the SAVE command:
SAVE "a:filename",a or SAVE "b:filename",a
The LOAD Command.
-----------------
When you are ready to put the program back into the computer from
the previously recorded on disk, just type in the command:
LOAD "a:filename" or LOAD "b:filename"
Where "a:" is the designation for your first floppy drive, and
"filename" is the same filename as you used when the program was
originally saved. If you have a second floppy drive its designation is
"b:".
If you don't remember or don't know the filename that your friend
used, you can type in the FILES command, and the computer will display
a listing of filenames previously saved on the diusk. The format for
this command is:
FILES "a:" or FILES "b:"
The REM Command.
----------------
REM is short for "remark". The REM command is totally unnecessary
in any computer program. (Then why teach it?) The REM command allows
the programmer to put notes within the body of the program that he/she
can refer to, but that the computer will ignore. These notes can
include the program title, the author, the date of creation (for
copyright purposes), explanations of certain commands or formulae, etc.
No matter what is typed after the REM command (on that line), it
becomes part of the "statement" and the computer will bypass it as if
it was not present.
The END and STOP Commands.
--------------------------
Both of these commands serve the same purpose. Both commands tell
the computer to "stop" running. Both commands cause the "Ok" message
to be displayed along with the "flashing cursor". (Then why are there
two different commands?) The STOP command additionally displays the
line number that contained the STOP command, as: "Break in 150". A
complicated program may have more than one way to "stop". The
programmer may want to know which STOP command caused the program to
terminate.
In the programs shown we did not include an END nor STOP command
because is was not necessary. Most computers understand that when they
have no more commands to process (at the bottom of the program) an END
command is automatically assumed. An END or STOP command may
optionally be included at the bottom of a program.
The GOTO Command.
-----------------
The GOTO command is used whenever you want a program to "go to" a
different line other than the next line; the statement contains the
line number where the program is to go. This command gives the program
the ability to go back and repeat sections, or to go forward and jump
over sections of a program. (Some programmers call this action
jumping, branching or transfering.)
Another Program.
----------------
A teacher wants to write a program to grade each student's test.
The number of questions is to be entered only once, and then the number
of correctAnswers for that student. The program is to calculate the
student's grade in percent.
10 REM Grades - 4/14/84
30 INPUT "How many questions";Q
40 PRINT
50 INPUT "How many correct answers";A
60 G=100*A/Q
70 PRINT "Grade =";G;"%"
80 GOTO 40
You will want to "stop" this program after entering the last
student. The program has no END nor STOP command. The "assumed end"
at the bottom of the program is negated by the GOTO in line 80. On
most computers, pressing the "Break" or "Escape" key(s) will termimate
the program. Let's enhance the program by having the computer
calculate the class average in percent. In order to simplify the
process, we will show theAverage of the all students entered to that
point. The average is calculated by keeping a running total or sum of
all grades and dividing it by the number of students.
10 REM Grades - version 2 - 4/14/84
12 S=0
14 N=1
30 INPUT "How many questions";Q
40 PRINT
50 INPUT "How many correct answers";A
60 G=100*A/Q
70 PRINT "Grade =";G;"%"
72 S=S+G
74 AV=S/N
76 PRINT "Average =";AV;"%"
78 N=N+1
80 GOTO 40
Where lines 12, 14, 72, 74, 76, and 78 have been added.
The IF...THEN Command.
----------------------
The real power of the computer is released when we allow the
computer to make decisions. The computer makes decisions by making
comparisons, such as: does one variable equal another variable or
constant, is a variable negative, is one variable greater than another
variable or constant, etc. The IF...THEN commands gives us this
decision making capability. The general form of the command is:
IF logical expression THEN line number or command
The statement is interpreted as: "IF the logical expression is true,
THEN either goto that line, or do that command indicated after the
THEN. Conversely, IF the logical expression is false, then proceed to
the next line, bypassing the remainder of the statement after the
"then".
Logical Operators.
------------------
The usual logical comparisons are allowed within the IF logical
expression portion of the statement. They include the following
symbols slightly modified for computer usage, and are called "logical
operators":
= Equal to
> Greater than
< Less than
>= Greater than or equal to, => is also allowable
<= Less than or equal to, <= " " " "
<> Not equal to, >< " " " "
Further Enhancing the Program.
------------------------------
We can use the IF...THEN command in a number of ways to improve
the "Grade" program:
1. Make sure that there is at least one test question,
2. Make sure that there aren't more answers than questions, and
3. Allow the program to stop if a negative number of answers are
entered.
To incude these features in the program add the following lines:
35 IF Q<1 THEN 100
100 PRINT "Improper number of questions"
110 PRINT "please reenter..."
120 GOTO 30
55 IF A>Q THEN 150
150 PRINT "Too many correct answers"
160 PRINT "please reenter..."
170 GOTO 50
57 IF A<0 THEN END
Each group of new lines corresponds to each newly added feature.
Lines 35 and 55 have line numbers after the "then" while line 57 has an
END command after the "then".
Comparison Conjuctions.
-----------------------
It is possible to make more than one comparison within the logical
expression portion of the IF...THEN command. The conjuctions are:
AND both comparisons must be true in order for the entire logical
expression to be true, and
OR either one (or both) must be true in order for the entire
logical expression to be true.
The only stipulation is that each comparison must be able to stand
alone as a separate logical expresion.
Improper statements:
1000 IF X ABD Y = 0 THEN PRINT "both are zero"
1100 IF P OR Q <= 10 THEN 600
Correct statements:
1000 IF X=0 AND Y=0 THEN PRINT "both are zero"
1100 IF P<=10 OR Q<=10 THEN 600
There is one additional logical operator which permits the logical
expression to be negated; it is called NOT. Placing a NOT before a
logical expression will change its value to "false" if it was "true",
and vice-versa.
440 IF NOT(Z=6) THEN 330
450 IF NOT(A+B>5) THEN 980
In line 440 the computer will go to line 330 only when Z does NOT equal
6. In line 450 the computer will go to line 980 when the sum of A+B is
NOT greater than 5; that is, when the sum is less than or equal to 5.
A logical expression can always be rewritten to eliminate the NOT;
however, the "logic" may be difficult to envision. Remmember that
logical operators have the lowest level of hierarchy, thus the addition
in line 450 is always performed before the logical comparison is made.
If you are unsureOf the sequence of logical comparisons, insert
parentheses to force the desired sequence.
Exponentiation.
---------------
Besides the four arithmetic operators ("+" addition, "-"
subtraction, "*" multiplication, and "/" division) there is
exponentiation (carat, "^"), which means "raise to the power". If you
wanted to write Q raised to the 5th power, it would be:
75 P=Q^5 which is the same as 75 P=Q*Q*Q*Q*Q
In the hierarchy of operations, exponentiation is performed before the
other four arithmetic operations.
Parentheses.
------------
I previously said that there was an order to the way arithmetic
operations would be performed in a LET command (calculation). If you
have to change the order of the arithmetic operation, such as
performing an addition before a multiplication, then parentheses "( )"
must be used in sets. "(" is called the "left" or "open" parenthesis
and ")" is called the "right" or "close" parenthesis; there must be a
")" for every "(", and vice-versa. Whenever the computer sees a set of
parentheses it goes to the left-most, inner-most set and performs the
enclosed calculations, then progressively works to the outer-most set,
then it proceeds to the next (towards the right) inner-most set, and so
on.
Consider a fraction consisting of A+B in the numerator (top part)
and C+D in the denominator (bottom part). If the LET command was
writen:
35 X=A+B/C+D
The fractional part of the calculation would only be B/C, A and D would
be simply added to the fraction and not be part of it. If we enclose
the numerator within parentheses, giving the revised LET command:
35 X=(A+B)/C+D
Now the fractional part of the calculation would still not be correct
since the variable D would be added to the fraction rather than part of
the denominator. The correct way to write the LET command is:
35 X=(A+B)/(C+D)
On the computer you will find other symbols called "brackets, [ ]"
and "braces, { }"; they cannot be used in place of, or in addition to
parentheses.
Mathematical Functions.
-----------------------
Have you thought that you have bought one of the most expensive
four function programmable calculators. Don't get mad, you bought a
full, and I mean full, function scientific calculator, and more!
But you say, "I don't see any keys with scientific functions!"
They're there, but you'll have to use simple abbreviations to activate
them. Suppose you wanted to take the square root of X and store it in
Y, you'd write:
225 Y=SQR(X)
Where SQR( ) is the function abbreviation (name) and the parentheses
enclose the expression to be acted upon. The following is a list of
other common functions:
Function name Form of function
------------- ----------------
ABSolute value Y=BAS(X)
INTeger value Y=INT(X)
SiGNum (sign) Y=SGN(X)
natural LOG (ln) Y=LOG(X)
natural EXPonential Y=EXP(X)
SINe (trig.) Y=SIN(X) where X is in radians
COSine (trig.) Y=COS(X) " " " " "
TANgent (trig.) Y=TAX(X) " " " " "
ArcTaNgent (trig.) Y=ATN(X) " Y " " "
The parentheses are part of each function name and may not be
omitted. They are equivalent to normal parentheses (using the same
symbols "( )") in that the order of arithmetic operations considers
functions to be evaluated whenever their set of parentheses are
encountered.
Order of arithmetic & logical operations (hierarchy):
1. Inner-most parentheses & functions
2. Outer-most parentheses & functions
3. Exponentiation
4. Multiplication & division (left to right)
5. Addition & subtraction (left to right)
6. Logical comparative operations (=,<,>,etc.)
7. Logical conjunctive operations (AND, OR, NOT)